package main

import (
	"fmt"
	"strings"
)

func main() {
	//111221
	n := 5
	fmt.Println(countAndSay(n))
}

//#link: https://leetcode-cn.com/problems/count-and-say/
func countAndSay(n int) string {
	tmpMap := map[int]string{
		1: "1",
	}
	for i := 1; i <= n; i++ {
		if value, ok := tmpMap[i]; ok {
			tmpMap[i+1] = count(value)
		} else {
			break
		}
	}
	return tmpMap[n]
}

func count(str string) string {
	sb := &strings.Builder{}
	character, count := str[0], 1
	for i := 1; i < len(str); i++ {
		if str[i] == character {
			count++
		} else {
			sb.WriteString(fmt.Sprintf("%d%c", count, character))
			character = str[i]
			count = 1
		}
	}
	sb.WriteString(fmt.Sprintf("%d%c", count, character))
	return sb.String()
}
